#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"

void Usage(std::string cmd)
{
    std::cout << "please use : " << cmd << " server_ip server_port" << std::endl;
    exit(USAGE_ERROR);
}

//短服务
/* int main(int argc, char *argv[])
{
    if (argc != 3)
        Usage(argv[0]);

    std::string ip = argv[1];
    uint16_t port = (uint16_t)std::stoi(argv[2]);

    while (1)
    {
        // 1.创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(SOCKET_ERROR);
        }
        else
            std::cout << "socket success" << std::endl;

        // 2.bind 但是还是一样的，客户端不需要显示绑定对应的ip + 端口号，系统自己会做！

        // 3.那么，作为客户端需要进行listen，accept吗？ -> 不需要！
        // 但是，客户端需要主动connect!
        // connect后，上述的工作操作系统会全做了！
        InetAddr client(ip, port);

        int n = connect(sockfd, client.GetSockAddr_Ptr(), client.GetAddrSize());
        if (n != 0)
        {
            std::cerr << "connect error" << std::endl;
            exit(CONNECT_ERROR);
        }
        std::cout << "connect success" << std::endl;

        // 1.发消息
        std::string message;
        std::cout << "please enter : ";
        fflush(stdout);
        std::getline(std::cin, message);
        if (message == "")
            continue;
        ssize_t write_ret = write(sockfd, message.c_str(), message.size());
        (void)write_ret; // 偷懒

        // 2.收消息
        char buffer[1024] = {0};
        ssize_t read_ret = read(sockfd, buffer, sizeof(buffer) - 1);
        (void)read_ret; // 偷懒
        std::cout << buffer << std::endl;
    }

    return 0;
} */

// ./TCP_CLIENT.exe server_ip server_port
int main(int argc, char* argv[]){
    if(argc != 3) Usage(argv[0]);

    std::string ip = argv[1];
    uint16_t port = (uint16_t)std::stoi(argv[2]);

//1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) {
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERROR);
    }
    else std::cout << "socket success" << std::endl;

//2.bind 但是还是一样的，客户端不需要显示绑定对应的ip + 端口号，系统自己会做！

//3.那么，作为客户端需要进行listen，accept吗？ -> 不需要！
//但是，客户端需要主动connect!
//connect后，上述的工作操作系统会全做了！
    InetAddr client(ip, port);

    int n = connect(sockfd, client.GetSockAddr_Ptr(), client.GetAddrSize());
    if(n != 0) {
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERROR);
    }
    std::cout << "connect success" << std::endl;

    while(1){
        //1.发消息
        std::string message;
        std::cout << "please enter : " ;
        fflush(stdout);
        std::getline(std::cin, message);
        if(message == "") continue;
        ssize_t write_ret = write(sockfd, message.c_str(), message.size());
        (void)write_ret;//偷懒


        //2.收消息
        char buffer[1024] = {0};
        ssize_t read_ret = read(sockfd, buffer, sizeof(buffer) - 1);
        (void)read_ret;//偷懒
        std::cout << buffer << std::endl;
    }

    return 0;
}